package com.atguigu.champter5.Flink05.sink;

import com.atguigu.beans.WaterSensor;
import com.atguigu.source.RandomWaterSenson;
import com.mysql.jdbc.PreparedStatement;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.sql.SQLException;

public class Flink05_Sink_Mysql {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 10002);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);

        DataStreamSource<WaterSensor> ds = env.addSource(new RandomWaterSenson());

        ds.addSink(JdbcSink.sink(
                        "replace into sensor (id, ts, vc) values (?,?,?)",
                        new JdbcStatementBuilder<WaterSensor>() {
                            @Override
                            public void accept(java.sql.PreparedStatement preparedStatement, WaterSensor waterSensor) throws SQLException {
                                preparedStatement.setString(1, waterSensor.getId());
                                preparedStatement.setLong(2, waterSensor.getTs());
                                preparedStatement.setInt(3, waterSensor.getVc());
                            }
                        },
                        JdbcExecutionOptions.builder()
                                .withMaxRetries(5)
                                .withBatchSize(1000)
                                .withBatchIntervalMs(2000)
                                .build(),
                        new JdbcConnectionOptions
                                .JdbcConnectionOptionsBuilder()
                                .withUrl("jdbc:mysql://hadoop102:3306/test?useSSL=false")
                                .withUsername("root")
                                .withPassword("123321")
                                .withDriverName("com.mysql.jdbc.Driver")
                                .build()
                )
        );
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
